<template>
  <div
    v-if="moduleNameOptions&&activePageForm&&activePageForm.activeModuleIndex!=null"
    v-loading="loading"
    class="open-card-main"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-suffix="："
      size="small"
    >
      <div v-for="(v, k) in moduleNameOptions[form.type].params" :key="k">
        <!-- 图片类-->
        <el-form-item v-if="k == 'pic'" :label="v.label || '图片'" prop="biz.params.pic">
          <div class="upload-container">
            <el-upload
              :action="imageUploadUrl"
              :show-file-list="false"
              :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
              :before-upload="uploadImgBefore"
              :on-progress="uploadImgProgress"
              :on-error="uploadImgError"
              :on-success="
                (res, file) => {
                  return uploadImgSuccess(res, file, 'pic');
                }
              "
              :style="{ width: v.width + 'px', height: v.height + 'px' }"
              class="app-uploader-img-plus"
            >
              <el-image
                v-if="form.pic"
                :style="{ width: v.width + 'px', height: v.height + 'px' }"
                :src="fileBaseUrl + form.pic"
                class="img"
                fit="contain"
              />
              <i v-else :style="{ width: v.width + 'px', height: v.height + 'px' }" class="el-icon-plus" />
            </el-upload>
          </div>
          <el-button
            v-if="form.pic"
            type="text"
            round
            class="app-text-color-danger"
            style="padding-left: 0"
            @click="form.pic=null"
          >删除{{ v.label || '图片' }}
          </el-button>
          <div style="font-size: 12px">只能上传jpg/png/gif文件，建议像素{{ v.width + ' * ' + v.height }}，且不超过1MB</div>
        </el-form-item>

        <el-form-item label="默认卡" prop="biz.params.defaultCardId">
          <el-select v-model="form.biz.params.defaultCardId" placeholder="请选择" clearable="">
            <el-option
              v-for="(v,i) in cardList"
              :key="i"
              :label="v.status?v.categoryName:v.categoryName+'(已停用)'"
              :value="v.id"
              :disabled="!v.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开卡后" prop="biz.params.enableCardFields">
          <el-select v-model="form.biz.params.enableCardFields" placeholder="请选择">
            <el-option :value="true" label="显示会员信息卡片" />
            <el-option :value="false" label="隐藏会员信息卡片" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.biz.params.enableCardFields" label="会员信息卡片" prop="biz.params.cardFields">
          <el-checkbox-group v-model="form.biz.params.cardFields">
            <el-checkbox label="LEVEL">等级</el-checkbox>
            <el-checkbox label="BALANCE">余额</el-checkbox>
            <el-checkbox label="POINT">积分</el-checkbox>
            <el-checkbox label="CARD">卡</el-checkbox>
            <el-checkbox label="COUPON">券</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round @click="submit">保存</el-button>
          <el-button round @click="reset">重置</el-button>
        </el-form-item>
      </div>

      <!---->
    </el-form>

  </div>
</template>

<script>
import wxaBuildConfig from '@/views/wxaBuildModule/config'
import { mapGetters } from 'vuex'
import { getAllVipCardList } from '@/api/vip'
import { imgUploadUrl } from '@/api/upload'

export default {
  data() {
    return {
      // 配置
      // 校验字段相关
      rules: {
        'biz.params.cardFields': [
          {
            type: 'array',
            required: true,
            message: '请至少选择一种会员信息',
            trigger: ['blur', 'change']
          }
        ]
      },
      moduleNameOptions: null,
      imageUploadUrl: imgUploadUrl,
      // 状态
      loading: false,
      // 数据
      classifyCode: 'DEFAULT',
      cardList: [],
      form: {
        bg: '',
        biz: {
          params: {
            defaultCardId: null,
            enableCardFields: false,
            cardFields: []
          },
          type: 'OPEN_CARD'
        },
        color: '',
        content: '',
        dump: {
          appId: '',
          feature: '',
          featureParams: '',
          insidePage: '',
          insideParams: '',
          path: '',
          type: 'EMPTY',
          url: ''
        },
        modules: [],
        pic: '',
        ranking: 0,
        style: '',
        subTitle: '',
        subType: '',
        title: '',
        type: 'huiyuankaika'
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'activePageForm'])
  },
  watch: {
    'activePageForm.activeModuleIndex'() {
      this.fetchData()
    }
  },
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    this.moduleNameOptions = wxaBuildConfig[this.classifyCode].moduleName
    this.fetchData()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 获取数据
    fetchData() {
      this.getCardList()
      // 判断是否有数据
      if (this.activePageForm.modules[this.activePageForm.activeModuleIndex].modules.length) {
        this.mode = 'edit'
        this.form = JSON.parse(JSON.stringify(this.activePageForm.modules[this.activePageForm.activeModuleIndex].modules[0]))
      } else {
        this.mode = 'add'
        this.activePageForm.modules[
          this.activePageForm.activeModuleIndex
        ].modules = [JSON.parse(JSON.stringify(this.form))]
      }
    },

    // 获取卡列表
    getCardList() {
      this.loading = true
      getAllVipCardList().then(res => {
        this.cardList = res.data || []
      }).finally(() => {
        this.loading = false
      })
    },

    /**
     * 按钮组
     */
    // 保存
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          if (!params.biz.params.enableCardFields) {
            params.cardFields = []
          }
          this.activePageForm.modules[
            this.activePageForm.activeModuleIndex
          ].modules = [params]
          this.$notify({
            title: '成功',
            message: '已保存模块数据',
            type: 'success',
            duration: 2000,
            offset: 40
          })
        }
      })
    },

    // 重置
    reset() {
      this.$refs.form.resetFields()
    },

    // 上传图片前
    uploadImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ['JPG', 'PNG', 'GIF'])
    },

    // 上传图片中
    uploadImgProgress() {
      this.loading = true
    },

    // 上传图片错误
    uploadImgError() {
      this.loading = false
    },

    // 上传图片成功
    uploadImgSuccess(res, file, type) {
      this.loading = false
      if (res.code === 0) {
        this.form[type] = res.data.path
        this.$refs.form.clearValidate([type])
      } else {
        this.$message.error(res.msg)
      }
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.open-card-main {
  margin-top: 10px;
}

/* 上传图片 */
.upload-container {
  display: flex;

  .el-icon-plus {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    color: #8c939d;
  }

  .img {
    display: block;
  }
}

</style>
